﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kay.LazarToDo.Win.Common;
using Kay.LazarToDo.Win.Common._Enum;
using Kay.LazarToDo.Win.Models;

namespace Kay.LazarToDo.Win.AppServices
{
    /// <summary>
    /// 待办事项应用服务
    /// </summary>
    public class LazarToDoAppService
    {
        /// <summary>
        /// 获取所有项目
        /// </summary>
        /// <returns></returns>
        public IQueryable<TjlLazarToDo> GetAllList()
        {
            var query = GlobalVariables.DbContext.TjlLazarToDos.AsQueryable();
            query = query.OrderBy(r => r.State).ThenBy(r => r.CreationTime);
            return query;
        }

        /// <summary>
        /// 检查项目名称是否存在
        /// </summary>
        /// <param name="toDo">项目名称</param>
        /// <param name="projectId"></param>
        /// <returns>True存在，否则为False</returns>
        public bool CheckName(string toDo, Guid projectId)
        {
            var query = GlobalVariables.DbContext.TjlLazarToDos.AsQueryable();
            return query.Any(r => r.ToDo == toDo && r.Project.Id == projectId);
        }

        /// <summary>
        /// 保存项目
        /// </summary>
        /// <param name="name"></param>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public TjlLazarToDo SaveToDo(string name, Guid projectId)
        {
            var toDo = GlobalVariables.DbContext.TjlLazarToDos.Create();
            toDo.Id = Guid.NewGuid();
            toDo.ToDo = name;
            toDo.State = (int)ToDoState.ToDo;
            toDo.Project = GlobalVariables.DbContext.TjlProjects.Find(projectId);
            toDo.CreationTime = DateTime.Now;
            var toDoEntity = GlobalVariables.DbContext.TjlLazarToDos.Add(toDo);
            GlobalVariables.DbContext.SaveChanges();
            return toDoEntity;
        }

        /// <summary>
        /// 更新或删除待办事项
        /// </summary>
        /// <param name="id">待办标识</param>
        /// <param name="state">待办状态</param>
        /// <returns></returns>
        public TjlLazarToDo UpdateOrDeleteToDo(Guid id, ToDoState state)
        {
            var entity = GlobalVariables.DbContext.TjlLazarToDos.Find(id);
            if (entity == null)
                return null;
            if (state == ToDoState.Remove)
            {
                GlobalVariables.DbContext.TjlLazarToDos.Remove(entity);
            }
            else
            {
                entity.State = (int)state;
            }
            GlobalVariables.DbContext.SaveChanges();
            return entity;
        }
    }
}
